<?php
namespace app\admin\controller;

use \think\Validate as Validate;
class Upload extends Base{
    public function index(){
        $get = $this->req->get();
        $rule = [
            'action' => 'require'
        ];
        $validate = new Validate($rule);
        $result = '';
        if($validate->check($get)){
            $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("admin/vendor/ue/php/config.json")), true);
            $base_path=substr($_SERVER['SCRIPT_NAME'],0,strpos($_SERVER['SCRIPT_NAME'], '/Public'));
            foreach ($CONFIG as $k => $v) {
                if(in_array($k, array('imagePathFormat','scrawlPathFormat','snapscreenPathFormat','catcherPathFormat','videoPathFormat','filePathFormat','imageManagerListPath','fileManagerListPath'))){
                    $CONFIG[$k]=$base_path.$v;
                }
            }            
            switch($get['action']){
            case 'config':
                $result =  $CONFIG;
                break;
                
            case 'uploadimage':
                $result = $this->image();
                break;
            }
        }else{

            $result = [
                "state"    => "ERROR",
            ];
            
        }
        return json_encode($result);

        // $info = [
        //     "imageActionName" =>  "uploadimage",
        //     "state"    => "SUCCESS",
        //     "url"      => "/Upload/image/ueditor/20180708/1531013081486087.jpg",
        //     "title"    => "1531014344177032.jpg",
        //     "original" => "0cf996c7e8abb29a84f6a43980c7d419.jpg",
        //     "type"     => ".jpg",
        //     "size"     => 365519
        // ];
        // header("Content-Type: text/html; charset=utf-8");
        // return json_encode($info);

    }

    /**
     * image
     * 
     * @return 
     * @date Sun Jul  8 09:40:48 2018
     */
    protected function image(){
        $file = $this->req->file('upfile');
        $result = [];
        if($file){
            // $path = ROOT_PATH.'/files/images';
            // echo $path;
            // var_dump($file);
            $info = $file->move(ROOT_PATH . '/public/Uploads/images/');
            if($info){
                // 成功上传后 获取上传信息
                // 输出 jpg
                // echo $info->getExtension();
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                $result = [
                    "state"    => "SUCCESS",
                    "url"      => "/Uploads/images/".$info->getSaveName(),
                    "title"    => $info->getFilename(),
                    "original" => $info->getFilename(),
                    "type"     => $info->getExtension(),
                ];

            }else{
                $result = [
                    'state' => 'ERROR'
                ];
            }
        }
        return $result;
    }
}
